package ua.com.alus.resvac.crm.services.spring;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ua.com.alus.resvac.crm.domen.dao.ResumeDao;
import ua.com.alus.resvac.crm.domen.entities.Resume;
import ua.com.alus.resvac.crm.domen.entities.ResumeFile;
import ua.com.alus.resvac.crm.domen.prototype.DocType;

import java.util.List;

/**
 * ResumeService implementation
 * <p/>
 * Created by Usatov Alexey
 */
public class ResumeServiceImpl implements ResumeService {
    private LuceneService luceneService;

    public void setLuceneService(LuceneService luceneService) {
        this.luceneService = luceneService;
    }

    private ResumeDao resumeDao;

    public ResumeDao getResumeDao() {
        return resumeDao;
    }

    public void setResumeDao(ResumeDao resumeDao) {
        this.resumeDao = resumeDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveResume(Resume resume) {
        Resume mergedResume = getResumeDao().merge(resume);
        try {
            luceneService.indexRecord(mergedResume);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Resume getResume(String resumeUuid) {
        return resumeDao.findById(resumeUuid);
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = false)
    public List<Resume> getResumes(String accountUuid) {
        return getResumeDao().getEntityManager().createNamedQuery(Resume.SELECT_RESUME_BY_ACC_UUID).setParameter("accountUuid", accountUuid).getResultList();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteResumeFile(String uuid) {
        getResumeDao().getEntityManager().createNativeQuery(ResumeFile.NATIVE_DELETE_NATIVE_QUERY).setParameter(1, uuid).executeUpdate();
        try {
            luceneService.deleteRecord(uuid, DocType.RESUME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<String> getResumeFilesUuid(String resumeUuid) {
        return getResumeDao().getEntityManager().createNativeQuery(ResumeFile.NATIVE_SELECT_RESUME_FILES_UUID).
                setParameter(1, resumeUuid).getResultList();
    }
}
